/**
 * TODO websocket封装
 * 2020年3月19日14:30:03
 */
const config = require('./config.js')
const app = getApp();
const host = config.websocketServer; // websocket服务器baseUrl
let sotk = null;
let socketOpen = false;

function ws_connect(reMsg, id) {
  sotk = wx.connectSocket({
    url: host + id,
    header: {
      'content-type': 'application/json'
    }
  })
  sotk.onOpen(res => {
    socketOpen = true;
    console.log('监听 WebSocket 连接打开事件。', res);
  })
  sotk.onClose(onClose => {
    socketOpen = false;
    console.log('监听 WebSocket 连接关闭事件。', onClose)
  })
  sotk.onError(onError => {
    socketOpen = true;
    console.log('监听 WebSocket 错误。错误信息', onError)
  })
  // 收到消息
  sotk.onMessage(onMessage => {
    reMsg(onMessage.data);
  })
}

function sendMsg(msg, success) {
  if (socketOpen) {
    sotk.send({
      data: JSON.stringify(msg)
		},success())
  }
}

function getMessages(reMsg) {
  if (socketOpen) {
    sotk.onMessage(onMessage => {
      reMsg(onMessage.data);
    })
  }
}

module.exports.ws_connect = ws_connect;
module.exports.sendMsg = sendMsg;
module.exports.getMessages = getMessages;